package com.lb.shopguide.ui.fragment.guide.pay;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.zxing.WriterException;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.order.CommitOrderReplyBean;
import com.lb.shopguide.event.guide.GiveupPayEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.dialog.DialogChangePayType;
import com.lb.shopguide.ui.dialog.DialogMakeSure;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BarcodeUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.lb.shopguide.util.lb.ClickUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.SupportFragment;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/6/9.
 */

public class FragmentPayWechat extends BaseCommonFragment {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.iv_shop_logo)
    ImageView ivShopLogo;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_change_type)
    TextView tvPayType;
    @BindView(R.id.tv_sure_pay_order)
    TextView tvConfirmPayOrder;
    @BindView(R.id.iv_barcode)
    ImageView ivBarcode;

    private CommitOrderReplyBean mReplyBean;
    private String mMemberCode;
    private String payMode;

    public static FragmentPayWechat newInstance(CommitOrderReplyBean replyBean, String memberCode) {
        FragmentPayWechat fragmentPayWechat = new FragmentPayWechat();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.COMMIT_REPLY_BEAN, replyBean);
        bundle.putString(AppConstant.MEMBER_CODE, memberCode);
        fragmentPayWechat.setArguments(bundle);
        return fragmentPayWechat;
    }




    @Override
    public int getLayoutId() {
        return R.layout.fragment_pay_wechat;
    }

    @Override
    public void initData() {
        mUserConfigManager = UserConfigManager.getInstance(mContext);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.COMMIT_REPLY_BEAN)) {
            mReplyBean = (CommitOrderReplyBean) bundle.getSerializable(AppConstant.COMMIT_REPLY_BEAN);
            payMode = mReplyBean.getPayMode();
        }
        if (bundle.containsKey(AppConstant.MEMBER_CODE)) {
            mMemberCode = bundle.getString(AppConstant.MEMBER_CODE);
        }
    }

    @Override
    public void initView() {
        ntb.setTitleText("微信收款");
        ntb.setTitleColor(getResources().getColor(R.color.white));
        ntb.setBackground(Color.rgb(58, 166, 102));
        ntb.setLeftImageSrc(R.drawable.iv_back_white);
        ntb.setRightImageSrc(R.drawable.iv_refresh_barcode);
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBackDialog();
            }
        });
        ntb.setOnRightImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ClickUtil.isFastDoubleClick()) {
                    sendRequestRefreshQrCode(mReplyBean.getOrderNum());
                }
            }
        });
        bindData();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentPayWechat.class.getName();
    }

    private void bindData() {
        try {
            Bitmap bitmap = BarcodeUtil.createQRCode(mReplyBean.getPayQrCode(), (int) (210 * GuideApplication.getAppContext().getResources().getDisplayMetrics().density));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] bytes = baos.toByteArray();
            RequestOptions requestOptions = new RequestOptions()
                    .fitCenter()
                    .error(R.drawable.iv_default_avatar)
                    .priority(Priority.HIGH)
                    .diskCacheStrategy(DiskCacheStrategy.NONE);
            ImageLoaderUtils.getGlideManager().load(bytes).apply(requestOptions).into(ivBarcode);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        ImageLoaderUtils.displayCircle(mContext, ivShopLogo, mUserConfigManager.getStoreLogoUrl());
        tvPrice.setText("￥" + mReplyBean.getOrderTotalMoney());
    }

    @Override
    public boolean onBackPressedSupport() {
        showBackDialog();
        return true;
    }

    private void showBackDialog() {
        DialogMakeSure dialog = new DialogMakeSure(mContext);
        dialog.getDialog("是否放弃本次支付?").show();
        dialog.setOnDialogClickListener(new DialogMakeSure.OnDialogClickListener() {
            @Override
            public void onSure(DialogInterface dialog, int which) {
                EventBus.getDefault().post(new GiveupPayEvent());
                sendRequestCloseOrder();
            }

            @Override
            public void onCancel(DialogInterface dialog, int which) {
            }
        });
    }

    @OnClick(R.id.tv_change_type)
    void changeType() {
        if (mReplyBean.getPayMode() != null) {
            DialogChangePayType dialogChangePayType = DialogChangePayType.getDialogChangePayType(mReplyBean, mMemberCode);
            dialogChangePayType.show(getFragmentManager(),getPageTag());
        }
    }

    @OnClick(R.id.tv_sure_pay_order)
    void sureOrder() {
        sendRequestConfirmOrderPay(mReplyBean);
    }


    private void sendRequestRefreshQrCode(String orderNum) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mReplyBean = (CommitOrderReplyBean) JsonUtil.getObject(response.getReturnContent(), CommitOrderReplyBean.class);
                    mReplyBean.setPayMode(payMode);
                    bindData();
                }
            }
        };
        ApiMethodGuide.refreshQrCode(new SimpleLbObserver(listener, otherListener), orderNum, AppConstant.PAY_TYPE_WECHAT_PAY,this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestConfirmOrderPay(final CommitOrderReplyBean bean) {
        HashMap hashMap = new HashMap();
        hashMap.put("orderNum", mReplyBean.getOrderNum());
        hashMap.put("payMode", bean.getPayMode());
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    ((SupportFragment) getTopFragment()).start(FragmentPayResult.newInstance(true, bean));
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {
            @Override
            public void onSessionOutOfDate() {
                ((GuideMainActivity) getActivity()).onSessionOutOfDate();
            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort("确认支付订单异常");
            }
        };
        ApiMethodGuide.confirmOrderPay(new SimpleLbObserver(listener,errorListener),body,this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestCloseOrder() {
        HashMap hashMap = new HashMap();
        hashMap.put("orderNum", mReplyBean.getOrderNum());
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
                getActivity().finish();
            }
        };
        ApiMethodGuide.closeOrder(new SimpleLbObserver(listener,null),body,this, FragmentEvent.DESTROY_VIEW);
    }
}
